<?php

class Category extends My_Controller {
	
	var $data;	// data array
	
    public function __construct() {
        parent::__construct("chuyenmuc");
        $this->load->model('utility_model');
    }

    public function index() {		
        // Build data
        $this->data['dt'] = array(
            '0' => array(
                'id' => '1',
                'title' => 'Tiêu đề bài viết',
                'summary' => 'Tóm tắt bài viết',
        		'content' => 'Nội dung bài viết'               
            )
        );
        // Parser data       
        $this->template->parse_view('main_content' , 'category/edit.html' , $this->data);
        $this->template->parse_view('info_content' , 'category/info_content_edit.html' , $this->data);			
        // Render template
        $this->template->render();
    }
    
    public function viewEditCat($id){
    	$this->load->library('form_validation');
		//$this->load->library('onlinelib', '', TRUE);
		$this->form_validation->set_error_delimiters('<div style="color: red;">', '</div>');
    	$this->load->model('ngonngu_model');
    	$this->data['lang'] = $this->ngonngu_model->dsNgonngu();
    	// Build data    	
    	$this->load->model('chuyenmuc_model');
    	$this->data['dt'] = $this->chuyenmuc_model->xemchuyenmuc($id);        
        // Parser data       
        $this->template->parse_view('main_content' , 'category/edit.html' , $this->data);
       	$this->template->parse_view('info_content' , 'template/info_content_create.html' , $this->data);			
        // Render template
        $this->template->render();
    }
    
	public function viewAddCat(){
		$this->load->library('form_validation');
		//$this->load->library('onlinelib', '', TRUE);
		$this->form_validation->set_error_delimiters('<div style="color: red;">', '</div>');
		$this->load->model('ngonngu_model');
    	$this->data['lang'] = $this->ngonngu_model->dsNgonngu();
		$this->template->parse_view('main_content' , 'category/create.html' , $this->data);
        $this->template->parse_view('info_content' , 'template/info_content_create.html' , $this->data);
        // Render template
        $this->template->render();
	}    	
	
    public function loadChuyenmuc($ngonngu,$chuyenmuc)
    {
   	    $this->load->model('chuyenmuc_model');
    	$this->data = $this->chuyenmuc_model->laychuyenmucID($ngonngu);
    	echo "<select name='chuyenmuc'>";
    	foreach ($this->data as $row){
    	   if($chuyenmuc==$row['id_chuyenmuc']) $select="selected='selected'"; else $select="";
    		echo "<option value='".$row['id_chuyenmuc']."'".$select.">".$row['ten_chuyenmuc']."</option>";
    	}
    	echo "</select>";
    }
	
    public function viewAllCat($type){
		$this->data = array();
		switch ($type){
			case 'news':
				$session_data = array(
					'type' => 1
				);
				break;
			case 'video':
				$session_data = array(
					'type' => 2
				);
				break;
		}		
		$this->session->set_userdata($session_data);
		$this->template->parse_view('main_content' , 'category/table.html' , $this->data);
        // Render template
        $this->template->render();
    }
    
    public function addCat(){
    	$this->load->library('form_validation');
    	//$cat_id_user_create = $this->session->userdata('user_id');
		//$cat_name_user_create = $this->session->userdata('user_name');
		$this->form_validation->set_rules('title_category', 'Tiêu đề bài viết', 'xss_clean|required|min_length[5]|max_length[150]');				
		$title_category = $this->security->xss_clean($this->input->post('title_category'));
		$cat_type = $this->security->xss_clean($this->input->post('chuyenmuc'));
		//$status = $this->security->xss_clean($this->input->post('status'));
		$language = $this->security->xss_clean($this->input->post('language'));
		//$describe = $this->security->xss_clean($this->input->post('describe'));
		$id_mark = $this->utility_model->random();		
    	if ($this->form_validation->run() == FALSE){
			$this->viewAddCat();		
    	}
    	else{    		
			$result = $this->chuyenmuc_model->taochuyenmuc($title_category,$cat_type,$language,$id_mark,1,"Duy Hoan");    	
			if($result){
				switch($cat_type)
				{
					case 1:
						$link = base_url()."category/viewAllCat/news";
						break;
					case 2:
						$link = base_url()."category/viewAllCat/video";
						break;
					default:
						$link = "";
						break;
				}
?>
				   	<script type="text/javascript">
				   		alert('Thêm chuyên mục thành công!');
   						window.location = "<?php echo $link;?>";
					</script>
<?php	

			}		
    	}
    }
    
    public function editCat($id){
    	$this->load->library('form_validation');
    	//$cat_id_user_create = $this->session->userdata('user_id');
		//$cat_name_user_create = $this->session->userdata('user_name');
		$this->form_validation->set_rules('title_category', 'Tiêu đề bài viết', 'xss_clean|required|min_length[5]|max_length[150]');				
		$title_category = $this->security->xss_clean($this->input->post('title_category'));
		$cat_type = $this->security->xss_clean($this->input->post('ngonngu'));
		//$status = $this->security->xss_clean($this->input->post('status'));
		$language = $this->security->xss_clean($this->input->post('language'));
		$id_mark = $this->security->xss_clean($this->input->post('id_mark'));	
    	if ($this->form_validation->run() == FALSE){
			$this->viewEditCat($id);		
    	}
    	else{
    		$edit_date = date("Y-m-d H:i:s");    									
			$this->load->model('chuyenmuc_model');
    		$this->load->model('chuyenmuc_model');
			$result = $this->chuyenmuc_model->suachuyenmuc($id,$title_category,$cat_type,$language,$id_mark,1,"Duy Hoan",$edit_date);    	
			if($result){
				switch($cat_type)
				{
					case 1:
						$link = base_url()."category/viewAllCat/news";
						break;
					case 2:
						$link = base_url()."category/viewAllCat/video";
						break;
					default:
						$link = "";
						break;
				}
?>
				<script type="text/javascript">
					alert('Sửa chuyên mục thành công!');
   					window.location = "<?php echo $link;?>";
				</script>
<?php
			} 
    	}    	
    }

    public function delCat($id){
    	$this->load->model('chuyenmuc_model');
    	$result = $this->chuyenmuc_model->xoa($id);
    	if($result){
    		// Build data    	
    		$cat = $this->chuyenmuc_model->xemchuyenmuc($id);
    		$type = $cat['loaichuyenmuc'];
    		switch($type)
				{
					case 1:
						$link = base_url()."category/viewAllCat/news";
						break;
					case 2:
						$link = base_url()."category/viewAllCat/video";
						break;
				}    	
?>
	    	<script type="text/javascript">
				alert('Xóa chuyên mục thành công!');
   				window.location = "<?php echo $link;?>";
			</script>
<?php
    	}        	
    }
    
	public function showFinalCategoryDataTable(){
		$this->load->library('session');
		$aColumns = array('ten_chuyenmuc', 'ngaytao', 'ngaysua', 'ten_nguoitao', 'ngonngu', 'SUA', 'XOA');
		$_aColumns = array('id_chuyenmuc', 'ten_chuyenmuc', 'ngaytao', 'ngaysua', 'ten_nguoitao', 'loaichuyenmuc', 'id_mark', 'id_nguoitao', 'ngonngu.ngonngu');
		/* Indexed column (used for fast and accurate table cardinality) */
	    $sIndexColumn = "id_chuyenmuc";
	
	// DB table to use
	    $sTable = 'chuyenmuc';
	    
	    $iDisplayStart = $this->input->get_post('iDisplayStart', true);
	    $iDisplayLength = $this->input->get_post('iDisplayLength', true);
	    $iSortCol_0 = $this->input->get_post('iSortCol_0', true);
	    $iSortingCols = $this->input->get_post('iSortingCols', true);
	    $sSearch = $this->input->get_post('sSearch', true);
	    $sEcho = $this->input->get_post('sEcho', true);
		    
			 // Paging
	    if(isset($iDisplayStart) && $iDisplayLength != '-1' && $iDisplayLength != '0')
	    {
	        $this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
	    }
			// Ordering
	    if(isset($iSortCol_0))
	    {
	        for($i=0; $i<intval($iSortingCols); $i++)
	        {
	            $iSortCol = $this->input->get_post('iSortCol_'.$i, true);
	            $bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
	            $sSortDir = $this->input->get_post('sSortDir_'.$i, true);
	
	            if($bSortable == 'true')
	            {
	                $this->db->order_by($_aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
	            }
	        }
	    }
	    
		if(isset($sSearch) && !empty($sSearch))
	    {
	        for($i=0; $i<count($_aColumns); $i++)
	        {
	            $bSearchable = $this->input->get_post('bSearchable_'.$i, true);
	
	            // Individual column filtering
	            if(isset($bSearchable) && $bSearchable == 'true')
	            {
	                $this->db->or_like($_aColumns[$i], $this->db->escape_like_str($sSearch));
	            }
	        }
	    }
		// Select Data
	    $this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $_aColumns)), false);
	    $this->db->from('chuyenmuc');
	    $this->db->join('ngonngu','ngonngu.id_ngonngu = chuyenmuc.ngonngu');
	    //echo $this->session->userdata('type');
	    $this->db->where('loaichuyenmuc',$this->session->userdata('type'));	   
	    $rResult = $this->db->get();		
		    //$rResult = $this->db->get($sTable);
		    // Data set length after filtering
	    $this->db->select('FOUND_ROWS() AS found_rows');
	    $iFilteredTotal = $this->db->get()->row()->found_rows;
		    // Total data set length
    	$iTotal = $this->db->count_all($sTable);
		    // Output
	    $output = array(
	        'sEcho' => intval($sEcho),
	        'iTotalRecords' => $iTotal,
	        'iTotalDisplayRecords' => $iFilteredTotal,
	        'aaData' => array()
	    );		
			
		$result = $rResult->result_array();	
		foreach($result as $categories){
			$row = array();
			for ( $i=0 ; $i<count($aColumns) ; $i++ ){
				switch($aColumns[$i]){									
					case 'SUA':
						$row[] = "<a href='".base_url()."category/viewEditCat/".$categories['id_chuyenmuc']."'>Sửa/Duyệt</a>";						
						break;
					case 'XOA':
						$row[] = "<a href='".base_url()."category/delCat/".$categories['id_chuyenmuc']."'>Xóa</a>";		
						break;
					default:
						$row[] = $categories[$aColumns[$i]];
						break;
				}				
			}
			//print_r($output['aaData'][]);
			$output['aaData'][] = $row;
		}
		echo json_encode( $output );
	}

}